package com.itheima.ydd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.dto.MenuDto;
import com.itheima.ydd.entity.Menu;
import com.itheima.ydd.mapper.MenuMapper;
import com.itheima.ydd.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author yan.zhou
 * @since 2022-02-22
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuList(String role_id) {
        String[] strings = role_id.split(",");
        List<Menu> menuList = menuMapper.findMenuList(strings);
        return menuList;
    }

    //查询所有菜单
    @Override
    public List<MenuDto> allData() {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getPid, 0);
        List<Menu> menuList = this.list(queryWrapper);
        List<MenuDto> menuDtoList = menuList.stream().map(item -> {
            MenuDto menuDto = new MenuDto();
            BeanUtils.copyProperties(item, menuDto);
            getMenuList(menuDto);
            return menuDto;
        }).collect(Collectors.toList());
        return menuDtoList;
    }

    //子菜单查询
    public List<MenuDto> getMenuList(MenuDto menuDto) {
        LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Menu::getPid, menuDto.getId());
        List<Menu> list = this.list(queryWrapper);
        if (list == null) {
            return null;
        }
        List<MenuDto> menuDtoList = list.stream().map(item -> {
            MenuDto dto = new MenuDto();
            BeanUtils.copyProperties(item, dto);
            getMenuList(dto);
            return dto;
        }).collect(Collectors.toList());

        return menuDtoList;
    }
}
